<template>
  <Dialog
    v-model="dialogVisible"
    width="1200px"
    title="库存类型转换"
    :maxHeight="'800px'"
    :before-close="() => closeDialog(formRef)"
  >
    <el-form :model="form" ref="formRef" :rules="rules as FormRules" label-width="80px">
      <div class="w-full flex justify-between">
        <div class="w-45%">
          <el-form-item label="仓库">
            <el-select v-model="parentRow.wid" placeholder=" " clearable disabled>
              <el-option
                v-for="item in warehouseList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="商品编码">
            <el-input v-model="parentRow.product_code" disabled placeholder=" " />
          </el-form-item>
          <el-form-item label="算力">
            <el-input v-model="parentRow.hashrate" disabled placeholder=" " />
          </el-form-item>
          <el-form-item label="类型">
            <el-select v-model="parentRow.is_futures" placeholder=" " clearable disabled>
              <el-option
                v-for="item in warehouseTypeList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="可转数量">
            <el-input v-model="parentRow.pay_quantity" disabled placeholder=" " />
          </el-form-item>
          <!--          <el-form-item label="购买数量">-->
          <!--            <el-input v-model="parentRow.quantity" disabled placeholder=" " />-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="转换类型" prop="conversionType">-->
          <!--            <el-select-->
          <!--              v-model="form.conversionType"-->
          <!--              :placeholder="t('inventory.conversion.conversionTypeValidation')"-->
          <!--              @change="handleChangeIntoWarehouse"-->
          <!--            >-->
          <!--              <el-option-->
          <!--                v-for="item in conversionTypeOptions"-->
          <!--                :key="item.value"-->
          <!--                :label="item.label"-->
          <!--                :value="item.value"-->
          <!--              />-->
          <!--            </el-select>-->
          <!--          </el-form-item>-->
        </div>
        <div class="w-45%">
          <el-form-item label="商品名称">
            <el-input v-model="parentRow.product_name" disabled placeholder=" " />
          </el-form-item>
          <el-form-item label="品牌">
            <el-select v-model="parentRow.brand" placeholder=" " clearable disabled>
              <el-option
                v-for="item in brandList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="保修期">
            <el-input v-model="parentRow.expiration_date" disabled placeholder=" " />
          </el-form-item>
          <el-form-item label="到货日期">
            <el-input v-model="parentRow.arrival_date" disabled placeholder=" " />
          </el-form-item>
        </div>
      </div>
    </el-form>
    <!--      table-->
    <el-table
      :data="tableData"
      border
      class="m-t-10"
      :cell-style="{ textAlign: 'center' }"
      :header-cell-style="{ textAlign: 'center', background: '#f8f8f9', color: '#333333' }"
    >
      <el-table-column prop="warehouse_name" label="仓库" :show-overflow-tooltip="true" />
      <el-table-column prop="create_time" label="入库时间" :show-overflow-tooltip="true" />
      <el-table-column prop="inbound_batch" label="批次号" :show-overflow-tooltip="true" />
      <el-table-column prop="available_qty" label="可用库存数量" :show-overflow-tooltip="true" />
      <el-table-column label="是否可售" :show-overflow-tooltip="true">
        <template #default="{ row }">
          {{ row.is_sale === 1 ? '可售' : '不可售' }}
        </template>
      </el-table-column>
      <el-table-column prop="order_no" label="转换数量" :show-overflow-tooltip="true">
        <template #default="{ row }">
          <el-form
            :model="row"
            :ref="setConvertibleRuleRef"
            :hide-required-asterisk="true"
            class="py-4"
          >
            <el-form-item label="" prop="convertible_qty" :rules="convertibleRuleFn(row)">
              <el-input
                v-model="row.convertible_qty"
                placeholder="请输入转换数量"
                @input="(e: string) => (row.convertible_qty = e.replace(/^(0+)|\D+/g, ''))"
              />
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
    </el-table>
    <template #footer>
      <el-button class="m-r-4" @click="closeDialog(formRef)">
        {{ t('system.parameterConfig.cancel') }}
      </el-button>
      <el-button type="primary" @click="submit(formRef)">
        {{ t('order.confirm') }}
      </el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { type FormInstance, type FormRules, ElMessage, ElMessageBox, ElInput } from 'element-plus'
import { getInventoryEnumApi } from '@/api/wholesalOrder'
import {
  inventoryTypeConversionApi,
  getConversionListApi,
  getConversionTypeApi
} from '@/api/wholesalOrder'
import { oneDimensionalArraySummation } from '@/utils'

const emit = defineEmits(['refresh'])
const { t } = useI18n()

const dialogVisible = ref<boolean>(false)

const formRef = ref<FormInstance>()
const form = ref<Record<string, any>>({})

const parentRow = ref<Record<string, any>>({})

const tableData = ref<Array<Record<string, any>>>([])

const warehouseList = ref<Array<Record<string, any>>>([])
const warehouseTypeList = ref<Array<Record<string, any>>>([])
const brandList = ref<Array<Record<string, any>>>([])
const conversionTypeOptions = ref<Array<Record<string, any>>>([])

const rules = ref<FormRules>({
  conversionType: [
    {
      required: true,
      message: t('inventory.conversion.conversionTypeValidation'),
      trigger: 'change'
    }
  ]
})

const convertibleRuleRef = ref<FormInstance[]>([])

const setConvertibleRuleRef = (e) => {
  e && convertibleRuleRef.value.push(e)
}

const convertibleRuleFn = (row: Record<string, any>) => {
  return [
    {
      required: true,
      trigger: ['blur'],
      validator: (rule: Record<string, any>, value: string, callback: Function) => {
        if (!value) {
          callback()
        } else {
          if (parseFloat(value) > parseFloat(row.available_qty)) {
            callback(new Error(t('输入的转换数量不能大于可用库存数量')))
          } else {
            callback()
          }
        }
      }
    }
  ]
}

const submit = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate(async (valid) => {
    if (valid) {
      if (!tableData.value.length) return ElMessage.error('未匹配到库存数据，暂无法提交')
      if (tableData.value.every((item) => !item.convertible_qty))
        return ElMessage.error('请输入转换数量')
      const convertibleRuleResultList = await Promise.all(
        convertibleRuleRef.value.map(async (item) => await item.validate((valid) => valid))
      )
      if (!convertibleRuleResultList.every((item) => item)) return

      if (
        parseFloat(oneDimensionalArraySummation(tableData.value, 'convertible_qty', 0)) >
        parseFloat(parentRow.value.pay_quantity)
      )
        return ElMessage.error('列表内填写的转换数量总和不能为大于可转数量')

      ElMessageBox.confirm(
        '库存类型转换确认之后无法修改，请谨慎操作',
        t('purchase.logistics.tips'),
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(async () => {
          const resp = await inventoryTypeConversionApi({
            id: parentRow.value.id,
            productid: parentRow.value.product_id,
            arrival_date: parentRow.value.arrival_date,
            is_futures: 0,
            wid: parentRow.value.wid,
            list: tableData.value.flatMap((item) =>
              item.convertible_qty ? [{ id: item.id, quantity: item.convertible_qty }] : []
            )
          })
          if (resp.code === 0) {
            ElMessage.success('操作成功')
            closeDialog(formEl)
            emit('refresh')
          }
        })
        .catch(() => {})
    }
  })
}

const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  form.value = {}
  tableData.value = []
  convertibleRuleRef.value = []
  formEl.resetFields()
  dialogVisible.value = false
}

//选择转入仓库后重新查询底部列表数据
const handleChangeIntoWarehouse = async (e: number) => {
  // const resp = await getConversionListApi({
  //   product_id: parentRow.value.product_id,
  //   wid: parentRow.value.wid,
  //   arrival_date: parentRow.value.arrival_date,
  //   is_futures: e
  // })
  // tableData.value = resp.data
}

const getBackShow = async (row: Record<string, any>) => {
  parentRow.value = row
  const resp = await getInventoryEnumApi({ field: 'all' })
  brandList.value = resp.data.brand
  warehouseList.value = resp.data.wid
  warehouseTypeList.value = resp.data.is_futures
  // const conversionTypeResp = await getConversionTypeApi({ id: row.id })
  // conversionTypeOptions.value = conversionTypeResp.data
  const tableResp = await getConversionListApi({
    productid: parentRow.value.product_id,
    wid: parentRow.value.wid,
    arrival_date: parentRow.value.arrival_date,
    is_futures: 0
  })
  tableData.value = tableResp.data
}

defineExpose({
  dialogVisible,
  getBackShow
})
</script>
<style lang="less" scoped></style>
